package com.biodiv.miracle.web.interceptor;

import com.biodiv.miracle.web.handler.HandlerMethod;
import com.biodiv.miracle.web.handler.MappingObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: tianquan
 * @date: 2025-05-28  13:09
 * @description: 请求映射缓存
 */
public class RequestMappingCache {

    // POST ： POST/user/add
    private final Map<String, List<MappingObject>> requestMappingMap;

    // POST/user/add ： controller对应的方法
    private final Map<MappingObject, HandlerMethod> handlerMethodMap;

    public RequestMappingCache() {
        requestMappingMap = new HashMap<>(16);
        handlerMethodMap = new HashMap<>(64);
    }

    public MappingObject addRequestMapping(String requestMethod, String url) {
        List<MappingObject> mappingObjects = requestMappingMap.get(requestMethod);
        if (mappingObjects == null) {
            mappingObjects = new ArrayList<>();
        }
        MappingObject mappingObject = new MappingObject(requestMethod, url);
        mappingObjects.add(mappingObject);
        requestMappingMap.put(requestMethod, mappingObjects);
        return mappingObject;
    }

    public void addHandlerMethod(MappingObject mappingObject, HandlerMethod handlerMethod) {
        HandlerMethod old = handlerMethodMap.put(mappingObject, handlerMethod);
        if (old != null) {
            throw new RuntimeException(mappingObject.toString() + "重复");
        }
    }

    public HandlerMethod getHandlerMethod(String requestMethod, String url) {
        MappingObject mappingObject = new MappingObject(requestMethod, url);
        return handlerMethodMap.get(mappingObject);
    }

    public List<MappingObject> getRequestMapping() {
        ArrayList<MappingObject> list = new ArrayList<>();
        for (List<MappingObject> objects : requestMappingMap.values()) {
            list.addAll(objects);
        }
        return list;
    }

}
